/**
 * @(#)AdController.java 2017年4月10日
 * Copyright(C) 2017 ZHEXIN IT CO.,LTD. All rights reserved.
 */
package org.jsbd.boss.action;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.jsbd.boss.common.DataGridModel;
import org.jsbd.boss.common.ResponseMapUtils;
import org.jsbd.boss.common.ResponseUtils;
import org.jsbd.boss.domian.InviteCodeBean;
import org.jsbd.boss.domian.channel.InviteConfig;
import org.jsbd.boss.domian.channel.InviteConfigProbability;
import org.jsbd.boss.service.IInviteCodeService;
import org.jsbd.boss.util.NumUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * TODO 请加入本类的说明
 * 
 * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
 * @version 1.0.0
 */
@RequestMapping("/invite/code")
@Controller
public class InviteCodeController {
	public static final Logger LOGGER = LoggerFactory.getLogger(InviteCodeController.class);

	@Resource
	private IInviteCodeService inviteCodeService;

	@RequestMapping(value = "save")
	@ResponseBody
	public Map<String, Object> saveInviteCode(InviteCodeBean inviteCodeBean) {
		inviteCodeService.saveInviteCodeNew(inviteCodeBean);
		return ResponseMapUtils.responseSuccess();
//		inviteCodeService.saveInviteCode(inviteCodeBean);
//		return ResponseMapUtils.responseSuccess();
	}

	@RequestMapping(value = "get")
	@ResponseBody
	public Map<String, Object> getInviteCode(String mark) {
		String inviteCode = inviteCodeService.selectInviteCode(mark);
		if (StringUtils.isBlank(inviteCode)) {
			return ResponseMapUtils.responseFail("邀请码获取不到");
		}
		return ResponseMapUtils.responseSuccess(inviteCode);
	}

	@RequestMapping(value = "config/list")
	public String list(Model model) {
		return "invite/list";
	}

	@RequestMapping(value = "config/listJson")
	@ResponseBody
	public Map<String, Object> listJson(DataGridModel page, InviteConfig inviteConfig) {
		return inviteCodeService.getConfigList(page, inviteConfig);
	}

	@RequestMapping(value = "config/add", method = RequestMethod.GET)
	public String toAdd(Model model) {
		return "invite/add";
	}

	@RequestMapping(value = "config/add", method = RequestMethod.POST)
	public void add(Model model, InviteConfig inviteConfig, HttpServletResponse response) {
		try {
			String mark = inviteConfig.getMark();
			boolean flag = inviteCodeService.hasMark(mark);
			if (!flag) {
				ResponseUtils.responseMarkNotExists(response);
			} else {
				inviteCodeService.add(inviteConfig);
				ResponseUtils.responseSuccess(response);
			}
		} catch (Exception e) {
			ResponseUtils.responseFailure(response);
		}
	}

	@RequestMapping(value = "config/{id}/update", method = RequestMethod.GET)
	public String toUpdate(Model model, @PathVariable("id") Integer id) {
		InviteConfig inviteConfig = inviteCodeService.getById(id);
		model.addAttribute("inviteConfig", inviteConfig);
		return "invite/update";
	}

	@RequestMapping(value = "config/{id}/update", method = RequestMethod.POST)
	public void update(InviteConfig inviteConfig, HttpServletResponse response) {
		try {
			inviteCodeService.update(inviteConfig);
			ResponseUtils.responseSuccess(response);
		} catch (Exception e) {
			ResponseUtils.responseFailure(response);
		}
	}

	@RequestMapping(value = "config/{id}/delete", method = RequestMethod.POST)
	public void delete(@PathVariable Integer id, HttpServletResponse response) {
		try {
			inviteCodeService.delete(id);
			inviteCodeService.deleteInviteCodeProbability(id);
			ResponseUtils.responseSuccess(response);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
			ResponseUtils.responseFailure(response);
		}
	}
	
	@RequestMapping(value = "config/configProbability/{start}/{end}/{id}", method = RequestMethod.GET)
	public String toConfigProbability (Model model, @PathVariable Integer start, @PathVariable Integer end,
			@PathVariable Integer id) {
		List<InviteConfigProbability> list = inviteCodeService.getInviteCodeProbability(id);
		Integer s = 0;
		Integer e = 0;
		if (list.size() > 0) {
			s = list.get(0).getTotalCount();
			e = list.get(list.size()-1).getTotalCount();
		}
		if(null == list || list.size()==0 || !(s.intValue() == start.intValue() && e.intValue() == end.intValue())) {
			//inviteCodeService.deleteInviteCodeProbability(id);
			list.clear();
			for (int i = start; i <= end; i++) {
				InviteConfigProbability icp = new InviteConfigProbability();
				icp.setInviteId(id);
				icp.setTotalCount(i);
				list.add(icp);
			}
		}
		model.addAttribute("icps", list);
		model.addAttribute("id", id);
		model.addAttribute("start", start);
		model.addAttribute("end", end);
		return "invite/configProbability";
	}
	
	@RequestMapping(value = "config/configProbability", method = RequestMethod.POST)
	public void configProbability (Model model, HttpServletRequest request, HttpServletResponse response) {
		try {
			Integer inviteId = Integer.valueOf(request.getParameter("inviteId"));
			Integer start = Integer.valueOf(request.getParameter("start"));
			Integer end = Integer.valueOf(request.getParameter("end"));
			
			List<InviteConfigProbability> list = new ArrayList<InviteConfigProbability>();
			Float totalCountAvg = 0.0f;
			for (int i = start; i <= end; i++) {
				InviteConfigProbability icp = new InviteConfigProbability();
				icp.setInviteId(inviteId);
				icp.setTotalCount(i);
				Float probability = Float.valueOf(request.getParameter("totalCount"+i));
				icp.setProbability(probability);
				
				float b = NumUtil.multiply(i, probability);
				totalCountAvg = NumUtil.add(totalCountAvg, b);
				list.add(icp);
			}
			inviteCodeService.updateTotalCountAvg(inviteId, totalCountAvg);
			inviteCodeService.deleteInviteCodeProbability(inviteId);
			inviteCodeService.saveInviteCodeProbability(list);
			ResponseUtils.responseSuccess(response);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
			ResponseUtils.responseFailure(response);
		}
	}

}
